package cn.nami.web.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

public class WebUtil
{
	private static final Logger logger = Logger.getLogger(WebUtil.class.getName());
	private static final String regex = "^\\s*<string>(.*)</string>\\s*$";
	private static final Pattern pattern = Pattern.compile(regex);
	
	private static final String IP_ADDRESS_WEB_SERVICE = "http://www.webxml.com.cn/WebServices/IpAddressSearchWebService.asmx/getCountryCityByIp?theIpAddress=";
	
	private WebUtil()
	{
	};

	/**
	 * get the real ip address.
	 */
	public static String getIpAddr(HttpServletRequest request)
	{
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
		{
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
		{
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
		{
			ip = request.getRemoteAddr();
		}
		return ip;
	}
	
	/**
	 * get the address by ip
	 */
	public static String getAdress(String ip)
	{
		if("127.0.0.1".equals(ip) || "localhost".equals(ip))
		{
			return ip;
		}
		String address = null;
		try
		{
			URL url = new URL(IP_ADDRESS_WEB_SERVICE + ip);
			BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
			String line = null;

			while ((line = reader.readLine()) != null)
			{
				Matcher matcher = pattern.matcher(line);
				if(StringUtil.isNotEmpty(line) && matcher.find())
				{
					address = matcher.group(1);
					if(!ip.equals(address))
					{
						break;
					}
				}
			}
			reader.close();
		}
		catch (Exception e)
		{
			e.printStackTrace();
			logger.severe("Get address error..." + e.getMessage());
		}
		return address;
	}
}